package xxhui.space.newsclient;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import xxhui.space.newsclient.Bean.User;
import xxhui.space.newsclient.Bean.UserData;
import xxhui.space.newsclient.Http.NewsLoader;
import xxhui.space.newsclient.util.MyApplication;
//修改昵称页面
public class ModifyNicknameActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "ModifyNicknameActivity";
    @BindView(R.id.me_info_modify_nickname_toolbar)
    Toolbar toolbar;
    @BindView(R.id.me_info_modify_ed)
    EditText ed_nickname;
    @BindView(R.id.me_info_modify_but)
    Button but_save;
    @BindView(R.id.me_info_modify_ed_clean)
    ImageView iv_clean;
    private Handler handler;
    private NewsLoader loader = new NewsLoader();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_modify_nickname);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        handler =new Handler();
        User user = MyApplication.getUser();
        if(user!=null){
            ed_nickname.setText(user.getNickname());
            ed_nickname.setSelection(ed_nickname.getText().length());
        }

        setSupportActionBar(toolbar);
        ActionBar actionBar =  getSupportActionBar();
        if(actionBar != null) {
            //取消默认标题，并显示返回按钮
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowTitleEnabled(false);
        }

        iv_clean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ed_nickname.setText("");
            }
        });
        but_save.setOnClickListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //点击back键finish当前activity
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        String nickname = ed_nickname.getText().toString();
        if(nickname.equals("")){
            return;
        }
        loader.modifyNickName(nickname).subscribe(new Consumer<UserData>() {
            @Override
            public void accept(UserData userData) throws Exception {
                Log.i(TAG, "accept: "+userData);
                if(userData!=null){
                    if(userData.getCode()==0){
                        MyApplication.setUser(userData.getData());
                        finish();
                    }
                    Toast.makeText(ModifyNicknameActivity.this, userData.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.i(TAG, "accept: error"+throwable);
            }
        });

    }

//    @Override
//    public void onClick(View view) {
//        String nickname = ed_nickname.getText().toString();
//        if(nickname.equals("")){
//            return;
//        }
//        OkHttpClient okHttpClient = MyApplication.getOkHttpClient();
//        StringBuilder builder = new StringBuilder();
//        builder.append("http://interview.jbangit.com/user/nickname");
//        final String loginUrl = builder.toString();
//        System.out.println(loginUrl);
//        FormBody.Builder fBuilder = new FormBody.Builder();
//        fBuilder.add("nickname", nickname);
//        RequestBody formBody = fBuilder.build();
//        Request request = new Request.Builder().url(loginUrl).post(formBody).build();
//        OkHttpCallback callback = new OkHttpCallback() {
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String result = response.body().string();
//                System.out.println("success!");
//                System.out.println(result);
//                JSONObject jsonObject = null;
//                try {
//                    jsonObject = new JSONObject(result);
//                    if (jsonObject == null) {
//                        return;
//                    }
//                    int code = jsonObject.getInt("code");
//                    final String message = jsonObject.getString("message");
//                    if (code == 0) {
//                        MyApplication.setIsLogin(true);
//                        UserData userData = new Gson().fromJson(result, new TypeToken<UserData>() {
//                        }.getType());
//                        //Log.i(TAG, "onResponse: "+userData.toString());
//                        MyApplication.setUser(userData.getData());
//                        finish();
//                    }
//                    handler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            Toast.makeText(ModifyNicknameActivity.this, message, Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onFailure(Call call, IOException e) {
//                System.out.println("error is happen");
//                handler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(ModifyNicknameActivity.this, "网络出现了点小差错，请重试", Toast.LENGTH_SHORT).show();
//                    }
//                });
//            }
//        };
//        okHttpClient.newCall(request).enqueue(callback);
//        setResult(0);
//    }
}
